package hw6;

import java.util.*;

public class InfixCalculator {
	
	public void evaluate(String strExpression) {
		ArrayListStack<Character> operatorStack = new ArrayListStack<Character>();
		ArrayListStack<Float> operandStack = new ArrayListStack<Float>();
		String[] splitExpression = strExpression.split(" ");
		Float result = null;
		boolean valid = true;
		
		try {
			// Initial loop that parses expression and does multiplication and division
			for (int i = 0; i < splitExpression.length; i++) {
				try {
					float operand = Float.parseFloat(splitExpression[i]);
					operandStack.push(operand);
				} catch (NumberFormatException e) {
					if (splitExpression[i].charAt(0) == '*') {
						operandStack.push(operandStack.pop() * Float.parseFloat(splitExpression[i+1]));
						i++;
					} else if (splitExpression[i].charAt(0) == '/') {
						operandStack.push(operandStack.pop() / Float.parseFloat(splitExpression[i+1]));
						i++;
					} else {
						operatorStack.push(splitExpression[i].charAt(0));
					}
				}
			}
			
			while (!operatorStack.empty()) {
				switch (operatorStack.pop()) {
					case '+':
						operandStack.push(operandStack.pop() + operandStack.pop());
						break;
					case '-':
						operandStack.push(operandStack.pop() - operandStack.pop());
						break;
					default:
						System.out.println("Unsupported symbol found");
						return;
				}
			}
			
			result = operandStack.pop();
			
			if (!operandStack.empty()) {
				System.out.println("Invalid infix notation");
				return;
			}
			
			System.out.println(result);
			
		} catch (EmptyStackException e) {
			System.out.println("Invalid infix notation");
			return;
		} catch (StringIndexOutOfBoundsException e) {
			System.out.println("Invalid infix notation");
			return;
		}
	}
	
	
}
